import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
// import store from '../store'
import localStorage from '../utils/localStorage'
// import { debounce } from '@/utils/index'
// import router from '../router'

const // 时间戳字段
  timeLabel = [
    'create_time'
  ]

const http = axios.create()

// 请求拦截器
http.interceptors.request.use(
  config => {
    let data, k

    try {
      data = JSON.parse(JSON.stringify(config.data))
    } catch {
      data = {}
    }

    for (k in data) {
      if (k === 'offset') {
        // 分页
        data[k] = (data[k] - 1) * data.length
      } else if (timeLabel.includes(k)) {
        // 时间戳
        data[k] = parseInt(data[k] / 1000)
      }
    }

    config.data = data
    // if (getToken()) {
    config.headers.accesslogin = getToken()
    // }
    config.baseURL = process.env.VUE_APP_BASE_URL

    return config
  },
  error => {
    console.log(error)
  }
)

http.interceptors.response.use(
  response => {
    const data = response.data
    // const dataData = data.data
    // console.log(dataData)
    // 登录
    if (data.token) localStorage.set('token', data.token)
    // console.log(dataData)
    // 路由
    // if (dataData.rules) store.commit('rulesMutations', dataData.rules)

    codeMessage(data.meta)

    return response
  },
  error => {
    // console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 提示错误信息
function codeMessage(data) {
  let msg = ''
  switch (data.status) {
    // 成功
    case 200:
      break
    // 500出现异常
    case 500:
      Message({
        message: data.message,
        type: 'error',
        duration: 5 * 1000
      })
      throw new Error(data.message || 'Error')
      // return Promise.reject(new Error(data.message || 'Error'))
    // 登录信息出现异常
    case 800:
      MessageBox.alert(data.message, {
        type: 'warning',
        center: true
      }).then(() => {
        return new Promise((resolve, reject) => {
          localStorage.del('token')
          resolve()
        }).then(() => {
          location.reload()
        })
      })
      return Promise.reject(new Error(data.message || 'Error'))
    case 900:
      msg = data.message
      break
    // 其它错误信息
    default:
      msg = data.message
      break
  }

  if (msg !== '') {
    Message({
      showClose: true,
      message: msg,
      type: 'error'
    })
  }
}

export default http
